package com.xdu.math.Controller;

import com.xdu.math.Config.Constant;
import com.xdu.math.Entity.CommonResponse;
import com.xdu.math.Entity.UserInfo;
import com.xdu.math.Service.UserService;
import com.xdu.math.Util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.server.ResponseStatusException;

@Controller
@RequestMapping(value="/rest")
@Slf4j
public class UserController {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserService userService;

    /**
     * 登陆接口，spring security验证用户
     * @param userInfo 用户信息 邮箱+密码
     * @return response data:userInfo message:token
     * */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public CommonResponse<UserInfo> authenticateUser(@RequestBody UserInfo userInfo){
        CommonResponse<UserInfo> response = new CommonResponse<>();
        try{
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            userInfo.getUserEmail(),
                            userInfo.getPassword())
            );
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            userService.refreshLastLogin(userInfo.getUserEmail());
            userInfo = userService.getUserInfoByEmail(userDetails.getUsername());
            String token = jwtUtil.generateToken(userDetails);
            response.setData(userInfo);
            response.setMessage(token);
            response.setCode(Constant.successCode);
        } catch(AuthenticationException e) {
            log.warn("用户 {} 尝试登陆但错误， {}",userInfo.getUserName(),e.getMessage());
            response.setMessage("账号或密码错误");
            response.setCode(Constant.errorCode);
        } catch (Exception e) {
            log.error("登录接口异常", e);
            response.setMessage("未知错误，请稍后重试");
            response.setCode(Constant.serverErrorCode);
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "系统异常", e);
        }
        return response;
    }

    /**
     * 注册接口
     * @param userInfo 用户信息 用户名+邮箱+密码
     * */
    @RequestMapping(value="/register")
    @ResponseBody
    public CommonResponse<String> registerUser(@RequestBody UserInfo userInfo){
        CommonResponse<String> response = new CommonResponse<>();
        try{
            response.setMessage(userService.registerUser(userInfo));
            if("success".equals(response.getMessage())){
                response.setCode(Constant.successCode);
            }else{
                response.setCode(Constant.errorCode);
            }
        }catch (Exception e){
            log.error(e.getMessage());
            response.setCode(Constant.serverErrorCode);
        }
        return response;
    }

    /**
     * 密码重置
     * @param userInfo
     * @return response
     * */
    @RequestMapping(value="/resetPass",method = RequestMethod.POST)
    @ResponseBody
    public CommonResponse<String> resetPass(@RequestBody UserInfo userInfo){
        CommonResponse<String> response = new CommonResponse<>();
        try{
            response.setMessage(userService.resetPass(userInfo));
            if("success".equals(response.getMessage())){
                response.setCode(Constant.successCode);
            }else{
                response.setCode(Constant.errorCode);
            }
        }catch (Exception e){
            log.error("密码修改发生错误, {}",e.getMessage());
            response.setMessage("服务器错误，请稍后重试");
            response.setCode(Constant.serverErrorCode);
        }
        return response;
    }
}
